package tools

import (
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"golang.org/x/crypto/bcrypt"
	"strconv"
)

func ParseFormStr(c *gin.Context, key string) string {
	return c.Request.FormValue(key)
}
func ParseFormStr2(c *gin.Context, key, value string) string {
	var v = ParseFormStr(c, key)
	if v == "" {
		return value
	}
	return v
}

func ParseFormInt(c *gin.Context, key string) int {
	if pStr := c.Request.FormValue(key); pStr != "" {
		var err error
		return StrToInt(err, pStr)
	}
	return 0
}

func ParseFormInt1(c *gin.Context, key string, value int) int {
	if pStr := c.Request.FormValue(key); pStr != "" {
		var err error
		return StrToInt(err, pStr)
	}
	return value
}

func StrToInt(err error, index string) int {
	result, err := strconv.Atoi(index)
	if err != nil {
		HasError(err, "string to int error"+err.Error(), -1)
	}
	return result
}

func CompareHashAndPassword(e string, p string) (bool, error) {
	err := bcrypt.CompareHashAndPassword([]byte(e), []byte(p))
	if err != nil {
		log.Print(err.Error())
		return false, err
	}
	return true, nil
}

// Assert 条件断言
// 当断言条件为 假 时触发 panic
// 对于当前请求不会再执行接下来的代码，并且返回指定格式的错误信息和错误码
func Assert(condition bool, msg string, code ...int) {
	if !condition {
		statusCode := 200
		if len(code) > 0 {
			statusCode = code[0]
		}
		panic("CustomError#" + strconv.Itoa(statusCode) + "#" + msg)
	}
}

// HasError 错误断言
// 当 error 不为 nil 时触发 panic
// 对于当前请求不会再执行接下来的代码，并且返回指定格式的错误信息和错误码
// 若 msg 为空，则默认为 error 中的内容
func HasError(err error, msg string, code ...int) {
	if err != nil {
		statusCode := 200
		if len(code) > 0 {
			statusCode = code[0]
		}
		if msg == "" {
			msg = err.Error()
		}
		log.Println(msg + ":" + err.Error())
		panic("CustomError#" + strconv.Itoa(statusCode) + "#" + msg)
	}
}

func HasError500(err error, msg string) {
	if err != nil {
		statusCode := 500
		if msg == "" {
			msg = err.Error()
		} else {
			msg += " : " + err.Error()
		}
		log.Println(err)
		panic("CustomError#" + strconv.Itoa(statusCode) + "#" + msg)
	}
}
